package com.bonuo.crm.service.impl;

import com.bonuo.crm.domain.*;
import com.bonuo.crm.domain.Process;
import com.bonuo.crm.mapper.*;
import com.bonuo.crm.service.NewspaperService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.entity.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Service
public class NewspaperServiceImpl implements NewspaperService {
    @Autowired
    private NewspaperMapper newspaperMapper;
    @Autowired
    private InformMapper informMapper;
    @Autowired
    private ClientMapper clientMapper;
    @Autowired
    private AgentMapper agentMapper;
    @Autowired
    private VisitMapper visitMapper;
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private ProcessMapper processMapper;
    @Autowired
    private ActivityMapper activityMapper;


    @Override
    @DataScope(provinceAlias = {"weekly_newspaper"})
    public List<Newspaper> selectNewspaperList(Newspaper newspaper) {
        return newspaperMapper.selectNewspaperList(newspaper);
    }

    @Transactional
    @Override
    public Integer insertNewspaper(Newspaper newspaper) {
        //查出这个用户在本周新增的内容
        String content = weeklyData(newspaper.getUserId());
        newspaper.setContent(content);
        // 添加一条周报信息
        Integer integer = newspaperMapper.insertNewspaper(newspaper);
        //在添加通知信息
        //先根据用户部门id查询出用户父级部门和祖父部门下所有用户
        List<SysUser> sysUsers = newspaperMapper.selectAllUserByDeptId(newspaper.getDeptId());
        //遍历用户信息插入通知
        for (SysUser sysUser : sysUsers) {
            //添加通知
            Inform inform = new Inform();
            inform.setReceiveId(Math.toIntExact(sysUser.getUserId()));
            inform.setContent(newspaper.getCreateBy()+"上传了一份新的周报，请及时查看");
            inform.setCreateBy(newspaper.getCreateBy());
            inform.setUpdateBy(newspaper.getUpdateBy());
            inform.setNewspaperId(newspaper.getId());
            integer = informMapper.insertInform(inform);
        }

        return integer;
    }

    @Override
    public Integer deleteNewspaperById(Integer id) {

        return newspaperMapper.deleteNewspaperById(id);
    }

    @Override
    public Integer updateNewspaper(Newspaper newspaper) {

        return newspaperMapper.updateNewspaper(newspaper);
    }

    @Override
    public Newspaper selectNewspaperById(Integer id) {
        return newspaperMapper.selectNewspaperById(id);
    }

    @Override
    public String weeklyData(Integer userId) {
        try {
        //本周新增客户列表及数量
        Map<String, Object> map = new LinkedHashMap<>();
        List<Client> weeklyClientList = clientMapper.selectWeeklyClientList(userId);
        map.put("weeklyClientCount",weeklyClientList.size());
        map.put("weeklyClientList",weeklyClientList);
        //本周新增代理商列表及数量
        List<Agent> weeklyAgentList = agentMapper.selectWeeklyAgentList(userId);
        map.put("weeklyAgentCount",weeklyAgentList.size());
        map.put("weeklyAgentList",weeklyAgentList);
        //本周新增拜访记录列表及数量
        List<Visit> weeklyVisitList = visitMapper.selectWeeklyVisitList(userId);
        map.put("weeklyVisitCount",weeklyVisitList.size());
        map.put("weeklyVisitList",weeklyVisitList);
        //本周新增项目列表及数量
        List<Project> weeklyProjectList = projectMapper.selectWeeklyProjectList(userId);
        map.put("weeklyProjectCount",weeklyProjectList.size());
        map.put("weeklyProjectList",weeklyProjectList);
        //本周新增项目进度列表及数量
        List<Process> weeklyProcessList = processMapper.selectWeeklyProcessList(userId);
        map.put("weeklyProcessCount",weeklyProcessList.size());
        map.put("weeklyProcessList",weeklyProcessList);
        //本周新增市场活动列表及数量
        List<Activity> weeklyActivityList = activityMapper.selectWeeklyActivityList(userId);
        map.put("weeklyActivityCount",weeklyActivityList.size());
        map.put("weeklyActivityList",weeklyActivityList);

        // 1. 创建 ObjectMapper 实例（Jackson 的核心工具类）
        ObjectMapper objectMapper = new ObjectMapper();

        // 2. 将 map 转换为 JSON 字符串
        String jsonStr = objectMapper.writeValueAsString(map);

        // 3. 存入数据库（假设使用你的 DAO 或 Service）
        // 例如：weeklyReportService.saveJsonData(userId, jsonStr);
        System.out.println("转换后的 JSON: " + jsonStr);

        return jsonStr;
        } catch (JsonProcessingException e) {
            // 处理 JSON 转换异常（如日志记录、抛出业务异常等）
            e.printStackTrace();
            throw new RuntimeException("数据转换为 JSON 失败", e);
        }

    }

    @Override
    public String selectNewspaperContentById(Integer id) {
        return newspaperMapper.selectNewspaperContentById(id);
    }
}
